package com.dhj.entity;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author DaHuaJia
 * @Description SpringSecurity UserDetails接口实现类
 * @Date 2022-03-20 13:10:26
 */
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private User user;

    private List<String> permissions;


    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }


    // 不做序列化处理，就不会报错到redis中，避免报错。
    @JSONField(serialize = false)
    // 存储SpringSecurity所需要的权限信息的集合
    private List<SimpleGrantedAuthority> authorities;


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 把permissions中String类型的权限信息封装成SimpleGrantedAuthority对象
        if (authorities != null) {
            return authorities;
        }

        /*
        // 方法一，for循环遍历
        authorities = new ArrayList<>();
        permissions.forEach(permission ->{
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
            permissionList.add(authority);
        });
        return permissionList;
        */

        // 方法二，数据流，函数式编程
        authorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return authorities;

    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    /**
     * 账户是否过期
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}
